<?php
namespace App\Utils\Service\Syj;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Response;

class Token extends Response
{
    private $key;
    private $token;
    private const tick="HS256";
    private $time;
    private $iss;
    private $aud;
    private $nbf;
    function __construct($key="user",$iss='',$aud='')
    {
        $this->time=time();
        $this->key=$key;
        $this->iss=config('api.jwtToken.iss','http://127.0.0.1/');
        $this->aud=config('api.jwtToken.aud','http://127.0.0.1/');
        $this->nbf=config('api.jwtToken.nbf',300);
    }
    function encode($data){
        $payload = [
            'iss' => $this->iss,
            'aud' => $this->aud,
            'iat' =>  time()-$this->nbf*60,
            'nbf' =>  time(),
            'user'=>$data
        ];
        $token = JWT::encode($payload, $this->key, self::tick);
        return $token;
    }
    function decode($token){
        //验证签名
        $data= JWT::decode($token, new Key($this->key, self::tick));
        //Token过期
        if ($this->time<$data->iat) return false;
        //验证通过返回用户信息
        return   $data->user;
    }
}
